//------------------------------------------------------------------------------
// <copyright company="Telligent Systems">
//     Copyright (c) Telligent Systems Corporation.  All rights reserved.
// </copyright> 
//------------------------------------------------------------------------------

using System;
using System.Collections;
using System.ComponentModel;
using System.Drawing;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using CommunityServer;
using CommunityServer.Components;
using CommunityServer.Controls;
using CommunityServer.Files.Components;

namespace CommunityServer.Files.Controls
{

	public class CreateEditEntry : FileGalleryTemplatedWebControl
	{
		CSContext csContext = CSContext.Current;

		#region Child Controls

		private TextBox Name;
		private CommunityServer.Controls.Editor Description;
		private HtmlInputHidden UploadGuid;
		private IText FormTitle;
		private IText FileName;
		protected TagEditor Tags;

		private ModalLink UploadFile;
		private IButton Save;
		private IButton Cancel;

		#endregion

		#region Public Properties

		[DefaultValue( "" )]
		public virtual string ApplicationKey
		{
			get
			{
				Object state = ViewState["ApplicationKey"];
				if(state != null)
					return (string)state;
				return "";
			}
			set { ViewState["ApplicationKey"] = value; }
		}

		[DefaultValue( 0 )]
		public virtual Int32 CategoryID
		{
			get
			{
				Object state = ViewState["CategoryID"];
				if(state != null)
					return (Int32)state;
				return 0;
			}
			set { ViewState["CategoryID"] = value; }
		}

		[DefaultValue( 0 )]
		public virtual Int32 EntryID
		{
			get
			{
				Object state = ViewState["PictureID"];
				if(state != null)
					return (Int32)state;
				return 0;
			}
			set { ViewState["PictureID"] = value; }
		}

		#endregion

		#region Skin

		protected override void AttachChildControls()
		{
			Tags = (TagEditor)FindControl( "Tags" );
			Name = (TextBox)FindControl( "EntryName" );
			Description = (CommunityServer.Controls.Editor)FindControl( "EntryDescription" );
//			EntryData = (HtmlInputFile)FindControl( "EntryFileToUpload" );
			FormTitle = FindText("FormTitle");
			FileName = FindText("FileName");
			UploadGuid = (HtmlInputHidden) FindControl("TempAttachmentGuid");

			Save = FindButton( "EntrySave" );
			Cancel = FindButton( "EntryCancel" );
			UploadFile = (ModalLink)FindControl("UploadFile");

			InitializeChildControls();
		}

		private void InitializeChildControls() 
		{
			Save.Click += new EventHandler(Save_Click);
			Cancel.Click += new EventHandler(Cancel_Click);
			Cancel.CausesValidation = false;
		}

		#endregion

		protected override void OnInit(EventArgs e)
		{
			base.OnInit(e);
			ApplicationKey = csContext.ApplicationKey;
			CategoryID = csContext.CategoryID;
			EntryID = csContext.PostID;

			// Access check
			if (EntryID != -1)
			{
				// Check permission against updating/deleting existing picture
				Folder folder = Folders.GetFolder(ApplicationKey);
				Entry entry = Entries.GetEntry(EntryID);
				Permissions.AccessCheck( folder, Permission.Post, csContext.User, Entries.GetEntry(EntryID) );

				if (csContext.User.Username != entry.Username || csContext.User.IsAnonymous || (folder.IsModerated && csContext.User.ModerationLevel != ModerationLevel.Unmoderated))
					throw new CSException(CSExceptionType.AccessDenied, "You do not have access to edit this file.");
			}
			else
			{
				// if PictureID = -1, then we are creating a new picture and only need to check
				// access agaisnt creating a new post to this Section.
				Permissions.AccessCheck( Folders.GetFolder(ApplicationKey), Permission.Post, csContext.User );

				Entries.CreateEntryAccessCheck();
			}
		}

		protected override void OnLoad(EventArgs e)
		{
			base.OnLoad(e);

			if (!Page.IsPostBack)
				this.DataBind();
			else
				EnsureChildControls();
		}

		public override void DataBind()
		{
			base.DataBind();

			// Populate the categories checkboxes
			if (Tags != null)
				Tags.AvailableTags = PostCategories.GetCategories(CurrentFolder.SectionID);

			if(EntryID != -1)
			{
				Entry entry = Entries.GetEntry(CurrentFolder.SectionID, EntryID);
				Name.Text = entry.Subject;
				Description.Text = entry.Body;
				FileName.Text = entry.Attachment.FileName;

				// Mark all of the picture's categories checked
				if (Tags != null)
				{
					ArrayList categories = Entries.GetEntryCategories(entry, false);
					string[] tags = new string[categories.Count];
					for(int i = 0; i < categories.Count; i++)
						tags[i] = ((PostCategory) categories[i]).Name;

					Tags.SelectedTags = tags;
				}

				UploadGuid.Value = "NotNew";
				FormTitle.Text = entry.Subject;
				UploadFile.Text = FileGalleryResourceManager.GetString("EntryAdmin_FileOrUrl_UpdateUpload");
			}
			else
			{
				Name.Text = "";
				Description.Text = "";
				FileName.Text = FileGalleryResourceManager.GetString("EntryAdmin_FileOrUrl_None");

				if (csContext.CategoryID > 0)
				{
					Tags.SelectedTags = new string[] { PostCategories.GetCategory(csContext.CategoryID, CurrentFolder.SectionID).Name };
				}

				FormTitle.Text = FileGalleryResourceManager.GetString("Files_UploadFile");
				UploadFile.Text = FileGalleryResourceManager.GetString("EntryAdmin_FileOrUrl_Upload");
			}

			
			UploadFile.Url = FileGalleryUrls.Instance().UploadFile(this.CurrentFolder.SectionID);

			// Set some resource labels
			Save.Text = FileGalleryResourceManager.GetString("Save");
			Cancel.Text = FileGalleryResourceManager.GetString("Cancel");

			Page.RegisterClientScriptBlock(this.ClientID, "<script language=\"javascript\">var currentActionButton;</script>");

			Save.Attributes.Add("onmousedown", "currentActionButton = 'Save';");
			Cancel.Attributes.Add("onmousedown", "currentActionButton = 'Cancel';");

			if(CurrentFolder.IsModerated)
				Page.RegisterOnSubmitStatement(this.ClientID, "if (currentActionButton == 'Save') { alert('" + FileGalleryResourceManager.GetString("File_ModerationAlert").Replace("'", "\'") + "'); }" );

		}

		private void Save_Click(object sender, EventArgs e)
		{
			try
			{
				if(EntryID == -1)
					CreateEntry();
				else
					UpdateEntry();

				// Finishing stuff
				if(!Globals.RedirectSiteUrl())
					Page.Response.Redirect(FileGalleryUrls.Instance().ViewFolder(ApplicationKey), true);
			}
			catch(InvalidFileException)
			{
				Label error = FindControl( "ErrorLabel" ) as Label;
				error.Text = "The file uploaded is either of an invalid type or is larger than the settings allow.";
				error.ForeColor = Color.Red;
				error.Visible = true;
			}
		}

		private void CreateEntry()
		{
			Entry entry = new Entry();

			entry.Subject = Name.Text;
			entry.Body = Description.Text;

			if (Tags != null)
				entry.Categories = Tags.SelectedTags;

			entry.IsApproved = !CurrentFolder.IsModerated || csContext.User.IsFileAdministrator || csContext.User.IsModerator || csContext.User.ModerationLevel == ModerationLevel.Unmoderated;
			Entries.Create(CurrentFolder.SectionID, entry, new Guid(UploadGuid.Value));

			// Get the PostID
			EntryID = entry.PostID;
		}

		private void UpdateEntry()
		{
			Entry entry = Entries.GetEntry(CurrentFolder.SectionID, EntryID);

			entry.Subject = Name.Text;
			entry.Body = Description.Text;

			if (Tags != null)
				entry.Categories = Tags.SelectedTags;

			if (UploadGuid.Value != String.Empty && UploadGuid.Value != "NotNew")
				Entries.Update(entry, new Guid(UploadGuid.Value));
			else
				Entries.Update(entry);
		}

		private bool CheckFileExtension(string extensionList, string extension)
		{
			string[] list = extensionList.Split(';');
			extension = extension.ToLower();

			foreach(string item in list)
				if(item.Trim().ToLower() == extension)
					return true;
			return false;
		}

		private void Cancel_Click(Object sender, EventArgs e)
		{
			if(!Globals.RedirectSiteUrl())
				csContext.Context.Response.Redirect( FileGalleryUrls.Instance().ViewFolder(ApplicationKey), true );
		}
	}
}
